#include "StdAfx.h"
#include "ColorBar.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


CColorBar::CColorBar()
{
	m_nKeysSize = 10;
	m_nKeysDist = 5;
}

CColorBar::~CColorBar()
{
}

int CColorBar::GetKeysSize() const
{
	return m_nKeysSize;
}

void CColorBar::SetKeysSize(int sz)
{
	m_nKeysSize = sz;
}

int CColorBar::GetKeysDist() const
{
	return m_nKeysDist;
}

void CColorBar::SetKeysDist(int d)
{
	m_nKeysDist = d;
}

void CColorBar::DrawColorBar(CDC* pDC, const CRect& rect, BOOL horis,
							 BOOL invert/* = FALSE*/, BOOL showKeys/* = TRUE*/) const
{
	CGdiObject* old = pDC->SelectStockObject(DC_PEN);

	CRect barRect = rect;

	if(showKeys)
		if(horis)
			barRect.bottom -= m_nKeysSize + m_nKeysDist;
		else
			barRect.right -= m_nKeysSize + m_nKeysDist;

	float st = 0.0f,
		  end = 0.0f;
	if(horis)
	{
		st = float(barRect.left);
		end = float(barRect.right);
	}
	else
	{
		st = float(barRect.top);
		end = float(barRect.bottom);
	}
	float fDelta = end - st;

	for(float i = st; i < end; i++)
	{
		float val = i - st;
		val = val/fDelta;
		if(invert)
			val = 1.0f - val;
		if(!horis)
			val = 1.0f - val;
		COLORREF cl = GetColor(val);
		pDC->SetDCPenColor(cl);
		if(horis)
		{
			pDC->MoveTo(int(i), barRect.top);
			pDC->LineTo(int(i), barRect.bottom);
		}
		else
		{
			pDC->MoveTo(barRect.left, int(i));
			pDC->LineTo(barRect.right, int(i));
		}
	}
	pDC->SelectObject(old);


	if(showKeys)
	{
		CGdiObject* old = pDC->SelectStockObject(DC_BRUSH);

		float delta = 0.0f;
		int keyHalfSize = m_nKeysSize/2;

		if(horis)
			delta = float(rect.right - rect.left);
		else
			delta = float(rect.bottom - rect.top);

		for(int i = 0; i < GetNumKeys(); i++)
		{
			const SColorKey* pKey = GetKey(i);
			float pos = pKey->m_pos;
			if(!invert)
				pos = 1.0f - pos;
			CRect rt;
			if(horis)
			{
				int x = rect.left + int(delta*pos);
				rt.left = x - keyHalfSize;
				rt.right = x + keyHalfSize;
				rt.top = rect.bottom - m_nKeysSize;
				rt.bottom = rect.bottom;
			}
			else
			{
				pos = 1.0f - pos;
				int y = rect.bottom - int(delta*pos);
				rt.left = rect.right - m_nKeysSize;
				rt.right = rect.right;
				rt.top = y + keyHalfSize;
				rt.bottom = y - keyHalfSize;
			}
			pDC->SetDCBrushColor(pKey->m_clr);
			pDC->Rectangle(rt);
		}
		pDC->SelectObject(old);
	}
}